/*

 Designer: DaBai 
 E-mail: jamesbaicn@gmail.com
 Last Modified: #2010-01-19 18:54#
 License: GNU GENERAL PUBLIC LICENSE Version 3

 Devices:
 1.	STC12C5A60S2 with 22.1184MHz crystal as the core microcontroller unit
 2.	L297N as the control signal of the step motors
 3. ULN2003A as the drive of motors
 4. MAX232 as the serial communication device.
 5. Step motors with 4 wires control motor

 Output Port of MCU:
 P1.1 as the direction control of Motor 0
 P1.2 as the direction control of Motor 1
 P1.3 as the PWM0 channel for Motor 0;
 P1.4 as the PWM1 channel for Motor 1;
 
 Notice:
 Start Monitor before MCU
*/

#include "include/includes.h"

void main(void){
	unsigned int uDATA;
	unsigned char uCMD,uCHK,uMODE;
	InitPWM();
	uart1_init();
	//Init Setup
	//uMode: 1->PC Control(default), 2->EEPROM Control, 3->EEPROM Write, 4->EEPROM CHK
	uMODE = 1;
	uart1_ready();
    while(1){
		if(finishedFlag == 1){
			//Process Started.
			//Format: DBYQ 1 2345 6, save in array receiveTmp[]
			
			//Convert data
			uCMD = receiveTmp[5];
			uDATA = receiveTmp[6]*0x1000 + receiveTmp[7]*0x100 + receiveTmp[8]*0x10 + receiveTmp[9];
			uCHK = receiveTmp[10];

			//check uCHK
			if(uCHK!=((uDATA+uCMD)%10))uart1_error();
			else{
				//Data receive correctly.
				if(uCMD==2)uMODE=uDATA;//Setup Running Mode

				if(uCMD==3 && uMODE==1){//In PC Control Mode
					switch(uDATA){
					case 1:dUp();break;//Up
					case 2:dUpRight();break;//Up Right
					case 3:dRight();break;//Right
					case 4:dDownRight();break;//Down Right
					case 5:dDown();break;//Down
					case 6:dDownLeft();break;//Down Left
					case 7:dLeft();break;//Left
					case 8:dUpLeft();break;//Up Left
					case 0:dStop();break;//Stop
					}
					(uDATA<9)?uart1_done():uart1_error();
				}
				
				if(uCMD==4 && uMODE==3); //EEPROM Write
				if(uCMD==4 && uMODE==4); //EEPROM CHK
			}

			//Process Finished.
			finishedFlag = 0;
		}
	}
}